package com.example.demo.controller;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.demo.common.Result;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    UserMapper userMapper;

    @PostMapping("/login")
    public Result<?> login(@RequestBody User user){
        User res=userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getId,user.getId()).eq(User::getPassword,user.getPassword()));
        if(res==null)
        {
            return Result.error("-1","用户名或密码错误");
        }
        return Result.success();
    }

    @PostMapping("/register")
    public Result<?> register(@RequestBody User user){
       User res=userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getId,user.getId()));
        if(res!=null)
        {
            return Result.error("-1","用户名已存在");
        }
        if(user.getRole()==null){
            user.setRole(5);
        }
        userMapper.insert(user);
        return Result.success();
    }


    @PostMapping
    public Result<?> save(@RequestBody User user){
        userMapper.insert(user);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<?> getById(@PathVariable long id){
        return Result.success(userMapper.selectById(id));
    }

    @PutMapping
    public Result<?> update(@RequestBody User user){
        userMapper.updateById(user);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<?> update(@PathVariable long id){
        userMapper.deleteById(id);
        return Result.success();
    }


}
